package moonhy.c2dm_client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import moonhy.c2dm_client.R;
import moonhy.c2dm_client.TabHostActivity;
import moonhy.c2dm_client.MainActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class httpConnectionManager {
	public boolean mStatus	= false;
	private String reg_id	= "";
	private String phone_no	= "";
	
	public httpConnectionManager(Context context){
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		reg_id		= prefs.getString(context.getString(R.string.REG_ID), "");
		phone_no	= prefs.getString(context.getString(R.string.PHONE), "");
		
        try {
//            ConnectivityManager nInfo = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
//            nInfo.getActiveNetworkInfo().isConnectedOrConnecting();
//            Log.d("C2DM", "Net avail:" + nInfo.getActiveNetworkInfo().isConnectedOrConnecting());

            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
               //Toast.makeText(context.getApplicationContext(), "net on", Toast.LENGTH_LONG).show();
            	//Log.d("C2DM", "Network available:true");
            	mStatus = true;
            } else {
            	//Toast.makeText(context.getApplicationContext(), "연결상태를 확인 후 다시 시도하세요.", Toast.LENGTH_LONG).show();
                //Log.d("C2DM", "Network available:false");
                mStatus = false;
            }
        } catch (Exception e) {
           Log.e("C2DM",""+e);
        }
	}
	
	public String readJSON(String url, Map<String, String> params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			// Get the deviceID
			//nameValuePairs.add(new BasicNameValuePair("DEV_ID", reg_id));
			nameValuePairs.add(new BasicNameValuePair("PHONE_NO", phone_no));
			
			if(params != null){
				Iterator<String> iterator = params.keySet().iterator();
			    while (iterator.hasNext()) {
			        String key = (String) iterator.next();
			        nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
			    }
			}
			
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			HttpResponse response = client.execute(post);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			
			
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e("C2DM", "HttpConnection Error!!!!!!!!! " + statusCode);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}
	
	public String readJSON_GET(String url, Map<String, String> params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		
		List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
		//nameValuePairs.add(new BasicNameValuePair("DEV_ID", reg_id));
		nameValuePairs.add(new BasicNameValuePair("PHONE_NO", phone_no));
		
		if(params != null){
			Iterator<String> iterator = params.keySet().iterator();
		    while (iterator.hasNext()) {
		        String key = (String) iterator.next();
		        nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
		    }
		}
		
		String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
		url += "?" + paramString;
		//Log.i("C2DM", "Http Request: " + url);
		HttpGet get = new HttpGet(url);
		
		try {
			HttpResponse response = client.execute(get);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			
			
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e("C2DM", "HTTP response error with error code " + statusCode);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.i("C2DM", "Http Response: " + builder.toString());
		return builder.toString();
	}
}
